package com.itheima.zxingdemo;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.graphics.Surface;
import ohos.agp.window.dialog.ToastDialog;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.media.camera.CameraKit;
import ohos.media.camera.device.Camera;
import ohos.media.camera.device.CameraConfig;
import ohos.media.camera.device.CameraDeviceCallback;
import ohos.media.camera.device.CameraStateCallback;
import ohos.media.image.Image;
import ohos.media.image.ImageReceiver;
import ohos.media.image.common.ImageFormat;
import ohos.media.image.common.Size;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

public class CameraDemo extends Ability {
    // 获取CameraKit对象
    private CameraKit mCameraKit;
    private String cameraId = null;
    private EventHandler cameraHandler = new EventHandler(EventRunner.create("camera"));
    private CameraConfig.Builder cameraConfigBuilder;
    private SurfaceProvider surfaceProvider;
    private Surface previewSurface;
    // 图像帧数据接收处理对象
    private ImageReceiver imageReceiver;
    // 拍照支持分辨率
    private Size pictureSize;
    private ImageSaver imageSaver;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
//        super.setMainRoute(CameraDemoSlice.class.getName());
        super.setUIContent(ResourceTable.Layout_ability_camera_demo);
        surfaceProvider= (SurfaceProvider) findComponentById(ResourceTable.Id_surfaceProvider_demo);
        previewSurface=surfaceProvider.getSurfaceOps().get().getSurface();
    }
    private void openCamera(){
        mCameraKit= CameraKit.getInstance(this);
        if (mCameraKit == null) {
            // 处理cameraKit获取失败的情况
            showToast("相机开启失败");
            return;
        }
        mCameraKit.createCamera(getCameraId(), new CameraStateCallback() {
            @Override
            public void onCreated(Camera camera) {
                cameraConfigBuilder = camera.getCameraConfigBuilder();
                if (cameraConfigBuilder == null) {
                    showToast("onCreated cameraConfigBuilder is null");
                    return;
                }
                // 配置预览的Surface
                cameraConfigBuilder.addSurface(previewSurface);
                // 配置拍照的Surface
                cameraConfigBuilder.addSurface(imageReceiver.getRecevingSurface());
                // 配置帧结果的回调
//                cameraConfigBuilder.setFrameStateCallback(frameStateCallbackImpl, cameraHandler);
                try {
                    // 相机设备配置
                    camera.configure(cameraConfigBuilder.build());
                } catch (IllegalArgumentException e) {
                    showToast("Argument Exception");
                } catch (IllegalStateException e) {
                    showToast("State Exception");
                }
            }

            @Override
            public void onCreateFailed(String cameraId, int errorCode) {
                super.onCreateFailed(cameraId, errorCode);
            }

            @Override
            public void onConfigured(Camera camera) {
                super.onConfigured(camera);
            }

            @Override
            public void onPartialConfigured(Camera camera) {
                super.onPartialConfigured(camera);
            }

            @Override
            public void onConfigureFailed(Camera camera, int errorCode) {
                super.onConfigureFailed(camera, errorCode);
            }

            @Override
            public void onReleased(Camera camera) {
                super.onReleased(camera);
            }

            @Override
            public void onFatalError(Camera camera, int errorCode) {
                super.onFatalError(camera, errorCode);
            }

            @Override
            public void onCaptureRun(Camera camera) {
                super.onCaptureRun(camera);
            }

            @Override
            public void onCaptureIdle(Camera camera) {
                super.onCaptureIdle(camera);
            }
        }, cameraHandler);
        mCameraKit.registerCameraDeviceCallback(new CameraDeviceCallback() {
            @Override
            public void onCameraStatus(String cameraId, int status) {
                super.onCameraStatus(cameraId, status);
            }

            @Override
            public void onPhysicalCameraStatus(String cameraId, int status) {
                super.onPhysicalCameraStatus(cameraId, status);
            }

            @Override
            public void onFlashlightStatus(String cameraId, int status) {
                super.onFlashlightStatus(cameraId, status);
            }
        }, cameraHandler);
    }
    public String getCameraId(){
        if (cameraId == null){
            String[] cameraIds = mCameraKit.getCameraIds();
            if (cameraIds != null && cameraIds.length>0){
                cameraId = cameraIds[0];
            }
        }

        return cameraId;
    }
    // 单帧捕获生成图像回调 Listener
//    private final ImageReceiver.IImageArrivalListener imageArrivalListener = new ImageReceiver.IImageArrivalListener() {
//        @Override
//        public void onImageArrival(ImageReceiver imageReceiver) {
//            StringBuffer fileName = new StringBuffer("picture_");
//            fileName.append(UUID.randomUUID()).append(".jpg"); // 定义生成图片文件名
//            File myFile = new File(dirFile, fileName.toString()); // 创建图片文件
//            imageSaver = new ImageSaver(imageReceiver.readNextImage(), myFile); // 创建一个读写线程任务用于保存图片
//            cameraHandler.postTask(imageSaver); // 执行读写线程任务生成图片
//        }
//    };
    // 保存图片, 图片数据读写，及图像生成见 run 方法
    class ImageSaver implements Runnable {
        private final Image myImage;
        private final File myFile;

        ImageSaver(Image image, File file) {
            myImage = image;
            myFile = file;
        }

        @Override
        public void run() {
            Image.Component component = myImage.getComponent(ImageFormat.ComponentType.JPEG);
            byte[] bytes = new byte[component.remaining()];
            component.read(bytes);
            FileOutputStream output = null;
            try {
                output = new FileOutputStream(myFile);
                output.write(bytes); // 写图像数据
            } catch (IOException e) {
                showToast("save picture occur exception!");
            } finally {
                myImage.release();
                if (output != null) {
                    try {
                        output.close(); // 关闭流
                    } catch (IOException e) {
                        showToast("image release occur exception!");
                    }
                }
            }
        }
    }
    private void takePictureInit() {
//        List<Size> pictureSizes = mCameraKit.getCameraAbility(getCameraId()).getSupportedSizes(ImageFormat.JPEG); // 获取拍照支持分辨率列表
//        pictureSize = getpictureSize(pictureSizes);// 根据拍照要求选择合适的分辨率
//        imageReceiver = ImageReceiver.create(Math.max(pictureSize.width, pictureSize.height),
//                Math.min(pictureSize.width, pictureSize.height), ImageFormat.JPEG, 5); // 创建 ImageReceiver 对象，注意 creat 函数中宽度要大于高度；5 为最大支持的图像数，请根据实际设置。
//        imageReceiver.setImageArrivalListener(imageArrivalListener);
    }
    private void showToast(String msg) {
        new ToastDialog(this).setContentText(msg).show();
    }
}
